const { task, src, dest, series, watch, parallel } = require('gulp');
const rename = require('gulp-rename');
const uglify = require('gulp-uglify-es').default;
const less = require('gulp-less');
const minifyCss = require('gulp-minify-css');
const extender = require('gulp-html-extend');
const del = require('del');
const connect = require('gulp-connect');

task('aa', function() {
  return console.log('test');
});
//拷贝lib
task('lib', function() {
  return src('./src/lib/**/*.*').pipe(dest('./dist/lib'));
});
//js拷贝压缩
task('js', () => {
  return src('./src/js/*.js')
    .pipe(dest('./dist/js'))
    .pipe(
      rename({
        suffix: '.min'
      })
    )
    .pipe(uglify())
    .pipe(dest('./dist/js'))
    .pipe(connect.reload());
});
//处理less
task('less', () => {
  return src('./src/less/*.less')
    .pipe(less())
    .pipe(
      rename({
        extname: '.css'
      })
    )
    .pipe(dest('./dist/css'))
    .pipe(minifyCss())
    .pipe(
      rename({
        suffix: '.min'
      })
    )
    .pipe(dest('./dist/css'))
    .pipe(connect.reload());
});
//处理图片
task('img', () => {
  return src('./src/images/*.*')
    .pipe(dest('./dist/images'))
    .pipe(connect.reload());
});
//处理html
task('html', () => {
  return src('./src/**/*.html')
    .pipe(extender())
    .pipe(dest('./dist'))
    .pipe(connect.reload());
});
//清空任务
task('clean', () => {
  return del('./dist');
});

//gulp监听文件变化
task('watch', () => {
  watch('./src/**/*.html', series('html'));
  watch('./src/less/*.less', series('less'));
  watch('./src/images/*.*', series('img'));
  watch('./src/js/*.js', series('js'));
  watch('./src/lib/**/*.*', series('lib'));
});

//自动刷新
task('connect', function() {
  connect.server({
    root: './dist',
    livereload: true,
    port: 9999
  });
});

//整合任务
task(
  'default',
  series(
    'clean',
    'less',
    'js',
    'img',
    'lib',
    'html',
    parallel('watch', 'connect')
  )
);
